#include "Socket.h"
#include "Logger.h"
#include <sys/types.h>
#include <sys/socket.h>
#include "InetAddress.h"
#include <strings.h>
#include <unistd.h>
#include <netinet/tcp.h>

Socket::~Socket() {
    ::close(sockfd_);
}

        
void Socket::bindAddress(const InetAddress& localaddr) {
    if (0 != ::bind(sockfd_, (sockaddr*)localaddr.getSockAddr(), sizeof(sockaddr_in))) {
        LOG_FATAL("bind sockfd fail\n");
    }
}

void Socket::listen() {
    if (0 != ::listen(sockfd_, 1024)) {
        LOG_FATAL("listen fail\n");
    }
}


/**
 * @brief 
 * 
 * @param peeraddr 
 * @return int 返回连接client，用来与clifd通信的connfd
 */
int Socket::accept(InetAddress* peeraddr) {
    sockaddr_in addr;
    socklen_t len;
    bzero(&addr, sizeof addr);
    int connfd = ::accept(sockfd_, (sockaddr *)&addr, &len);
    if (connfd >= 0) {
        peeraddr->setSockAddr(addr); //将peeraddr填充为client的InetAddress信息，外界就可以拿到client的地址信息
    }
    return connfd;
}

void Socket::shutdownWrite() {//半关闭，关闭写端
    if (::shutdown(sockfd_, SHUT_WR) < 0) {
        LOG_ERROR("shutdown write error\n");
    }
}


void Socket::setTcpNoDelay(bool on) {
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof optval);
}
void Socket::setReuseAddr(bool on) {
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
}
void Socket::setReusePort(bool on) {
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof optval);
}
void Socket::setKeepAlive(bool on) {
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof optval);
}